import React from 'react';
import { Layout, List, Typography, Tooltip, BackTop, Tag, Spin, message } from 'antd';
import { CalendarOutlined, CarryOutOutlined } from '@ant-design/icons/lib';
import { Link } from 'react-router-dom';
import moment from 'moment';



const { Title, Paragraph } = Typography;

const { Content } = Layout;

export default class Index extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      list: [],
      pageSize: 5,
      page: this.props.history.location.query.page ? this.props.history.location.query.page : 1,
      total: 0,
      spinning: true,
    };
    // console.log('state:', this.state.page);

    this.articlesUrl = '/api/v1/articles?page=';
    // if (this.props.history.location.query.page == null) {
    //   this.props.history.push('/?page=1');
    // }
  }

  formatTime(time) {
    return moment(parseInt(new Date(time).getTime())).format('YYYY-MM-DD HH:mm');
  }

  _getArticles(page, pageSize) {
    window.$http.get(this.articlesUrl + page + '&page_size=' + pageSize).then((res) => {
      this.setState({
        list: res.list,
        pageSize: res.pager.page_size,
        page: res.pager.page,
        total: res.pager.total_rows,
        spinning: false,
      });
    }).catch((reason => {
      console.log('reason', reason.message);
      message.error('服务异常');
      this.setState({ spinning: false });
    }));
  }


  componentDidMount() {
    this._getArticles(this.state.page, this.state.pageSize);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    // console.log('page:', this.props.history.location.query.page);
    this._getArticles(this.props.history.location.query?.page, this.state.pageSize);
    // eslint-disable-next-line no-restricted-globals
    scrollTo(0, 0);
  }


  render() {
    return (
      <Content className="site-layout"
               style={{
                 margin: '0 auto', paddingTop: 5,
                 display: 'flex', flexDirection: 'column',
                 // minWidth: 700,
                 maxWidth: 900,
               }}>
        <div className="site-layout-background" style={{ padding: 24, minHeight: 380 }}>
          <Spin size={'large'} spinning={this.state.spinning}>
            <List
              style={{ flex: 1 }}
              itemLayout="vertical"
              size="large"
              pagination={{
                onChange: page => {
                  this.props.history.push('/?page=' + page);
                  // this.setState({ spinning: true });
                  // this._getArticles(page, this.state.pageSize);
                  //
                  // // eslint-disable-next-line no-restricted-globals
                  // scrollTo(0, 0);
                },
                current: this.state.page,
                // current: this.state.page,
                pageSize: this.state.pageSize,
                total: this.state.total,
              }}
              dataSource={this.state.list}
              renderItem={item => (
                <List.Item key={item.id} style={{ backgroundColor: '#f6f6f6', marginBottom: 20 }}>
                  <Typography style={{ width: '85%', margin: '0 auto' }}>
                    <Link to={'/detail?id=' + item.id}><Title style={{ fontSize: 28 }}>{item.title}</Title></Link>
                    <div style={{ marginBottom: 10 }}>
                      <Tooltip placement="topRight" title="创建时间">
                        <span style={{ cursor: 'help' }}><CalendarOutlined/>{this.formatTime(item.created_at)}</span>
                      </Tooltip>

                      <Tooltip placement="topRight" title="修改时间">
                        <span style={{
                          margin: '0 10px',
                          cursor: 'help',
                        }}><CarryOutOutlined/>{this.formatTime(item.updated_at)}</span>
                      </Tooltip>

                      {item.tags?.map((item) => {
                        // console.log('item:', item);
                        return <Tag key={item.id} color="default">{item?.tag.name}</Tag>;
                      })}
                    </div>

                    <img src={item.cover_image_url} alt={item.cover_image_url}
                         style={{ marginBottom: 10, width: '100%' }}/>

                    <Paragraph style={{ textAlign: 'left', marginBottom: 15 }}>
                      {item.desc}
                    </Paragraph>
                  </Typography>

                </List.Item>
              )}
            />
          </Spin>

          <BackTop/>
        </div>
      </Content>
    );
  }
}
